<template>
  <div class="bphone-box">
    <form>
      <div class="input-box">
        <p>手机号</p>
        <input
          type="text"
          name="phone"
          maxlength="11"
          class="my-input"
          v-model="form.phone"
          placeholder="请输入手机号"
        />
      </div>
      <div class="input-box">
        <p>验证码</p>
        <input maxlength="6" type="text" name="code" id class="my-input" v-model="form.code" placeholder="请输入验证码" />
        <mu-button class="btn code-btn" @click="getcode" v-show="sendAuthCode">获取验证码</mu-button>
        <mu-button class="btn code-btn" v-show="!sendAuthCode">{{auth_time}}s重新获取</mu-button>
      </div>
    </form>
    <mu-button class="btn problem-btn" @click="bindphone">绑定手机号</mu-button>
  </div>
</template>

<script>
import store from "store";
import Vue from "vue";
import { Toast } from "vant";
import "vant/lib/toast/style/index";
import { bindMobile, sendSMS } from "@/api/api";

Vue.use(Toast);

export default {
  data() {
    return {
      isdis: true,
      sendAuthCode: true /*布尔值，通过v-show控制显示‘获取按钮’还是‘倒计时’ */,
      auth_time: 0 /*倒计时 计数器*/,
      form: {
        phone: this.$store.state.userinfo.mobile,
        code: ""
      }
    };
  },
  methods: {
    getcode() {
      let phone = this.form.phone;
      this.isdis = false;
      if (phone == "") {
        Toast("请输入手机号");
        return false;
      }
      if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone)) {
        Toast("手机号码有误，请重填");
        return false;
      }
      this.$api.sendSMS(phone).then(res => {
        if (res.data.code == 0) {
          Toast("发送验证码成功");
          this.sendAuthCode = false;
          this.auth_time = 60;
          var auth_timetimer = setInterval(() => {
            this.auth_time--;
            if (this.auth_time <= 0) {
              this.sendAuthCode = true;
              clearInterval(auth_timetimer);
            }
          }, 1000);
        } else {
          Toast(res.data.msg);
          return;
        }
      });
    },
    bindphone() {
      let phone = this.form.phone;
      let code = this.form.code;

      if (phone == "") {
        Toast("请输入手机号");
        return false;
      }
      if (this.isdis) {
        Toast("请先获取验证码");
        return;
      }
      if (code == "") {
        Toast("请填写验证码");
        return false;
      }

      this.$api.bindMobile(phone, code).then(res => {
        if (res.data.code == 0) {
          Toast("手机号绑定成功");
          //更新用户信息
          this.$api.accountInfo().then(res => {
            // console.log(res);
            this.$store.dispatch("setUser", res.data.result);
            store.set("user", { userinfo: res.data.result });
            if(this.$store.state.ChargingID){
                this.$router.push("/success")
            }else{
                this.$router.push("/mine");
            }
          });
        } else {
          Toast(res.data.msg);
        }
      });
    }
  }
};
</script>

<style>
</style>
